import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入store
import store from '@/store'
import { Toast } from 'vant'

// import login from '@/views/login'
// import layout from '@/views/layout'
// import home from '@/views/home'
// import ask from '@/views/ask'
// import video from '@/views/video'
// import mine from '@/views/mine'
// import UserEdit from '@/views/mine/UserEdit'
// import article from '@/views/article'

const login = () => import('@/views/login')
const layout = () => import('@/views/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const video = () => import('@/views/video')
const mine = () => import('@/views/mine')
const UserEdit = () => import('@/views/mine/UserEdit')
const article = () => import('@/views/article')

Vue.use(VueRouter)

const routes = [
  { name: 'login', path: '/login', component: login },
  { name: 'UserEdit', path: '/mine/edit', component: UserEdit },
  { name: 'article', path: '/article/:id', component: article },
  {
    name: 'layout',
    path: '/',
    component: layout,
    redirect: '/home',
    children: [
      { name: 'home', path: '/home', component: home },
      { name: 'ask', path: '/ask', component: ask },
      { name: 'video', path: '/video', component: video },
      {
        name: 'mine',
        path: '/mine',
        component: mine,
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置导航守卫
// 会在进入某个路由之前调用
// to：要去哪 -- 得到的路由信息对象，里面有path、name、meta等
// from：从哪来 -- 得到的路由信息对象，里面有path、name、meta等
// next： 放行函数，调用它就代表放行，不调用就代表不放行
//       里面可以写参数，代表放行到哪里去，$router.push能怎么用，next就能怎么用
router.beforeEach((to, from, next) => {
  /*
    思路：
      先区分一下哪些页面需要登录，哪些页面不需要登录
          如何区分？
            给他们打标签 --- 路由元信息
  */
  // 如果我要去的是mine，那就放行
  if (to.meta.needLogin) {
    // 如果有token
    if (store.state.user.tokenObj.token) {
      next()
    } else {
      // 弹出提示
      Toast('请先登录')
      // 没有token
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else {
    // 不需要登录的页面
    next()
  }
})

// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
